<?php


namespace app\controller;


use app\BaseController;
use think\facade\Db;
use think\Request;
use app\model\Communication as CommunicationModel;
use app\model\User as UserModel;
class Communication extends BaseController
{
    /**
     *文本消息的数据持久化
     */
    public function save_Message(){
        if($this->request->isAjax()){
            $message = input("post.");

            $datas['fromid']=$message['fromid'];
            $datas['fromname']= $this->getName($datas['fromid']);
            $datas['toid']=$message['toid'];
            $datas['toname']= $this->getName($datas['toid']);
            $datas['content']=$message['data'];
            $datas['time']=$message['time'];
            $datas['isread']=0;
            $datas['type'] = 1;
            $chat=CommunicationModel::create([
                'fromid'=>$datas['fromid'],
                'fromname'=>$datas['fromname'],
                'toid'=>$datas['toid'],
                'toname'=>$datas['toname'],
                'content'=>$datas['content'],
                'isread'=>$datas['isread'],
                'type'=>$datas['type']
            ]);
        }
    }

    /**
     * 根据用户id返回用户姓名
     */
    public function getName($uid){

        $userinfo = UserModel::where('userId',$uid)->field('userName')->find()->toArray();

        return $userinfo['userName'];
    }

    /**
     * 根据用户id获取聊天双方的头像信息；
     */

    public function get_head(){

        if($this->request->isAjax()){
            $fromid = input('fromid');
            $toid = input('toid');

            $frominfo = UserModel::where('userId',$fromid)->field('userImage')->find()->toArray();
            $toinfo = UserModel::where('userId',$toid)->field('userImage')->find()->toArray();

            return [
                'from_head'=>$frominfo['userImage'],
                'to_head'=>$toinfo['userImage']
            ];
        }
    }

    /**
     * 根据用户id返回用户姓名；
     */
    public function get_name(){

        if($this->request->isAjax()){
            $uid = input('uid');
            $toinfo = UserModel::where('userId',$uid)->field('userName')->find();
            return ["toname"=>$toinfo['userName']];
        }
    }

    /**
     * 页面加载返回聊天记录
     */
    public function load(){

        if($this->request->isAjax()){

            $fromid = input('fromid');
            $toid = input('toid');
            $count =  CommunicationModel::whereRaw('(fromid=:fromid and toid=:toid) || (fromid=:to and toid=:from)',['fromid'=>$fromid,'toid'=>$toid,'to'=>$toid,'from'=>$fromid])
                ->count('id');

            if($count>=10){

                $message =    CommunicationModel::whereRaw('(fromid=:fromid and toid=:toid) || (fromid=:to and toid=:from)',['fromid'=>$fromid,'toid'=>$toid,'to'=>$toid,'from'=>$fromid])->limit($count-10,10)->order('id')->select()->toArray();

            }else{
                $message =   CommunicationModel::whereRaw('(fromid=:fromid and toid=:toid) || (fromid=:to and toid=:from)',['fromid'=>$fromid,'toid'=>$toid,'to'=>$toid,'from'=>$fromid])->order('id')->select()->toArray();

            }

            return $message;

        }

    }
    /**
     * 上传图片，返回图片地址
     */
    public function uploadimg()
    {
        $file = $_FILES['file'];
        $fromid = input('fromid');
        $toid = input('toid');
        $online = input('online');

        $suffix =  strtolower(strrchr($file['name'],'.'));
        $type = ['.jpg','.jpeg','.gif','.png'];
        if(!in_array($suffix,$type)){
            return ['status'=>'img type error'];
        }

        if($file['size']/1024>5120){
            return ['status'=>'img is too large'];
        }

        $filename =  uniqid("chat_img_",false);
        $uploadpath = '.\\uploads\\';
        $file_up = $uploadpath.$filename.$suffix;
        $re = move_uploaded_file($file['tmp_name'],$file_up);

        if ($re) {
            $name = $filename . $suffix;
            $data['content'] = $name;
            $data['fromid'] = $fromid;
            $data['toid'] = $toid;
            $data['fromname'] = $this->getName($data['fromid']);
            $data['toname'] = $this->getName($data['toid']);
            $data['isread'] = 0;
            $data['type'] = 2;
            $message = CommunicationModel::create([
                'fromid' => $data['fromid'],
                'fromname' => $data['fromname'],
                'toid' => $data['toid'],
                'toname' => $data['toname'],
                'content' => $data['content'],
                'isread' => $data['isread'],
                'type' => $data['type']
            ])->toArray();
            if ($message['id']) {
                return ['status' => 'ok', 'img_name' => $name];
            } else {
                return ['status' => 'false'];
            }
        }
    }

    /**
     * @param $uid
     * 根据uid来获取它的头像
     */
    public function get_head_one($uid){

        $fromhead = UserModel::where('userId',$uid)->field('userImage')->find()->toArray();

        return $fromhead['userImage'];
    }

    /**
     * @param $fromid
     * @param $toid
     * 根据fromid来获取fromid同toid发送的未读消息。
     */
    public function getCountNoread($fromid,$toid){

        return CommunicationModel::where(['fromid'=>$fromid,'toid'=>$toid,'isread'=>0])->count('id');

    }

    /**
     * @param $fromid
     * @param $toid
     * 根据fromid和toid来获取他们聊天的最后一条数据
     */
    public function getLastMessage($fromid,$toid){

        $info = CommunicationModel::whereRaw('(fromid=:fromid&&toid=:toid)||(fromid=:from&&toid=:to)',['fromid'=>$fromid,'toid'=>$toid,'from'=>$toid,'to'=>$fromid])->order('id','DESC')->limit(1)->find()->toArray();

        return $info;
    }

    /**
     * 根据fromid来获取当前用户聊天列表
     */
    public function get_list(){
        if($this->request->isAjax()){
            $fromid = input('id');
            $info  = Db::name('communication')->where('toid',$fromid)->field('fromid,toid,fromname')->group('fromid,toid,fromname')->select()->toArray();
            //这里是说一共有多少条数据
            $rows = array_map(function($res){
                return [
                    'head_url'=>'http://api.tp6.com/'.$this->get_head_one($res['fromid']),
                    'username'=>$res['fromname'],
                    'countNoread'=>$this->getCountNoread($res['fromid'],$res['toid']),
                    'last_message'=>$this->getLastMessage($res['fromid'],$res['toid']),
                    'chat_page'=>"http://api.tp6.com/index/index?fromid={$res['toid']}&toid={$res['fromid']}"
                ];

            },$info);

            return $rows;
        }

    }

    public function changeNoRead(){
        if($this->request->isAjax()){

            $fromid = input('toid');
            $toid = input('fromid');
            $chat=CommunicationModel::where(['fromid'=>$fromid,"toid"=>$toid])->update(['isread'=>1]);
//            $chat->isread=1;
//            $chat->save();

        }

    }
    public function getOnRead(){
        if($this->request->isAjax()){
            $fromid = input('fromid');
            $count=CommunicationModel::where(['toid'=>$fromid,'isread'=>0])->count();
            return $count;
        }
    }

}